//
//  HBReadView.m
//  HeartBeat
//
//  Created by karong on 2023/9/12.
//

#import "HBReadView.h"

@implementation HBReadView

-(void)dealloc {
    if (_contentFrame) {
        CFRelease(_contentFrame);
    }
}

- (void)setContent:(NSAttributedString *)content {
    _content = content;
    [self setNeedsDisplay];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    CTFramesetterRef setterRef = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.content);
    CGPathRef pathRef = CGPathCreateWithRect(CGRectMake(16, 0, HBScreenWidth - 32, HBScreenHeight - (20 + HBStatusBarHeight + 20 + HBSafeAreaBottomHeight)), NULL);
    CTFrameRef frameRef = CTFramesetterCreateFrame(setterRef, CFRangeMake(0, 0), pathRef, NULL);
    if (setterRef) {
        CFRelease(setterRef);
    }
    if (pathRef) {
        CFRelease(pathRef);
    }
    self.contentFrame = frameRef;
}

- (void)drawRect:(CGRect)rect {
    if (!_contentFrame) {
        return;
    }
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
    CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CTFrameDraw(_contentFrame, ctx);
}

@end
